home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 7699 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.2 KB

  1. From: bxiao@msn.com (Bing Xiao)
  2. Subject: modifying a 'const' variable, a bug in VC++?
  3. Date: 25 Feb 96 06:54:20 -0800
  4. Message-ID: <00001a81+0000a7f1@msn.com>
  5. Path: news.msn.com!msn.com
  6. Newsgroups: comp.lang.c++
  7. Organization: The Microsoft Network (msn.com)
  8.  
  9. Although modifying a 'const' is not desired(and should
  10. be prohibited), the following code should be able to do
  11. that:
  12.  
  13. main()
  14. {
  15.     const int i = 1;
  16.     int* j = (int *)&i;     // cast a "const int*" to "int*". The     
  17.                     // compiler should allow it
  18.  
  19.     *j = 2;
  20.     cout << *j << newl;    // should print "2"
  21.     cout << i << newl;    // should print "2" too
  22. }
  23.  
  24. when i compile the program in VC++ 4.0, it compiles without any problem.
  25. However, when it runs, the result is:
  26. 2
  27. 1
  28.  
  29. When I run in debugger, I took a step-by-step watch to variable "i".
  30. before the last statement is executed, "i" has a value "2", however,
  31. when the left "<<" operator was executed(I mean the one in "cout << i")
  32. the actual parameter value passed to iostream::operator<<(int) is 1.
  33. That means, it actually execute iostream::operator<<(1).
  34.  
  35. I consider this a bug in VC++(The correct result should be 2\n2\n. 
  36. Any comments? I just want to get the concept of "const" clarified.
  37. Thanks.
  38.